import { IconDouyin } from '@/components/icon';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeibo from '@/components/icon/IconWeibo';
import { pageTophubRecord } from '@/services/api/api-tophub-record';
import { Tiny } from '@ant-design/plots';
import { LightFilter, ProColumns, ProFormSelect, ProTable } from '@ant-design/pro-components';
import { ActionType } from '@ant-design/pro-table';
import { Tag } from 'antd';
import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import DrawerHotRankDetails from '../hot/DrawerHotRankDetails';

interface DetailsRankProps {
  createdTimes: string[];
  rank: TophubRankData.RankListSo | undefined;
  onRefurbish: () => void;
}

const HotType = {
  '1': {
    icon: <IconWeibo width={24} height={24} />,
    name: '微博热搜',
    type: 1,
  },
  '2': {
    icon: <IconDouyin width={24} height={24} />,
    name: '抖音热榜',
    type: 2,
  },
  '4': {
    icon: <IconToutiao width={24} height={24} />,
    name: '头条热搜',
    type: 4,
  },
};

const DetailsRank: React.FC<DetailsRankProps> = ({ createdTimes, rank, onRefurbish }) => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();

  const [search, setSearch] = useState({
    hotName: '',
    createdTimes: createdTimes,
    datahubLevelIds: [2000, 3000],
    hotIsCitys: ['0', '1'],
  });

  useEffect(() => {
    setSearch({
      ...search,
      createdTimes: createdTimes,
    });
    actionRef.current?.reloadAndRest();
  }, [createdTimes]);

  useEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [rank]);

  const columns: ProColumns<TophubRecordData.RecordPage>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          热点
        </span>
      ),
      dataIndex: 'hotName',
      align: 'center',
      copyable: true,
      ellipsis: true,
      width: '50%',
      render: (dom, entity, index, action) => {
        const hotType = HotType[`${entity.hotType}`];

        return (
          <DrawerHotRankDetails
            dom={dom}
            hotIcon={hotType.hotIcon}
            hotName={hotType.hotName}
            hotType={hotType.hotType}
            hotCity={hotType.hotCity}
            hotId={entity.hotId}
            onRefurbish={function (): void {}}
          />
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          最高排名
        </span>
      ),
      width: '80px',
      dataIndex: 'hotMaxTopIndex',
      align: 'center',
      render: (dom, entity, index, action) => {
        if (entity.hotMaxTopIndex == 1) {
          return (
            <>
              <Tag
                style={{
                  marginRight: 0,
                  width: 32,
                  textAlign: 'center',
                }}
                color="#ff5e57"
              >
                {entity.hotMaxTopIndex}
              </Tag>
            </>
          );
        } else if (entity.hotMaxTopIndex == 2) {
          return (
            <Tag
              style={{
                marginRight: 0,
                width: 32,
                textAlign: 'center',
              }}
              color="#ffd32a"
            >
              {entity.hotMaxTopIndex}
            </Tag>
          );
        } else if (entity.hotMaxTopIndex == 3) {
          return (
            <Tag
              style={{
                marginRight: 0,
                width: 32,
                textAlign: 'center',
              }}
              color="#7bed9f"
            >
              {entity.hotMaxTopIndex}
            </Tag>
          );
        } else if (entity.hotMaxTopIndex <= 10) {
          return (
            <Tag
              style={{
                marginRight: 0,
                width: 32,
                textAlign: 'center',
                padding: 0,
              }}
              color="#ced6e0"
            >
              {entity.hotMaxTopIndex}
            </Tag>
          );
        } else {
          return <>{entity.hotMaxTopIndex}</>;
        }
      },
    },

    // {
    //   title: (
    //     <span
    //       style={{
    //         color: '#99a3b7',
    //         fontSize: 12,
    //         textAlign: 'center',
    //         fontWeight: 'normal',
    //       }}
    //     >
    //       时长/h
    //     </span>
    //   ),
    //   dataIndex: 'onlineDuration',
    //   align: 'center',
    //   render: (dom, entity, index, action) => {
    //     var duration = moment.duration(moment(entity.executeTime).diff(moment(entity.insertTime)));
    //     return <>{duration.asHours().toFixed(2)}</>;
    //   },
    // },
    // {
    //   title: (
    //     <span
    //       style={{
    //         color: '#99a3b7',
    //         fontSize: 12,
    //         textAlign: 'center',
    //         fontWeight: 'normal',
    //       }}
    //     >
    //       渠道
    //     </span>
    //   ),
    //   dataIndex: 'hotType',
    //   align: 'center',
    //   valueEnum: {
    //     1: { text: '微博' },
    //     2: { text: '抖音' },
    //     4: { text: '今日头条' },
    //   },
    //   width: '80px',
    // },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          范围
        </span>
      ),
      dataIndex: 'hotIsCity',
      align: 'center',
      width: '80px',
      valueEnum: {
        0: { text: '全国' },
        1: { text: '重庆' },
      },
      sorter: true,
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          首次上榜时间
        </span>
      ),
      dataIndex: 'hotInsertTime',
      align: 'center',
      width: '120px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          收录时间
        </span>
      ),
      dataIndex: 'createdTime',
      align: 'center',
      width: '100px',
      render: (dom, entity, index, action) => dayjs(entity.createdTime).format('MM-DD HH:mm'),
    },
  ];

  const TinyAreaChartsView = (dateDatas: { date: string; value: number }[]) => {
    const config = {
      data: dateDatas,
      width: 400,
      height: 80,
      padding: 8,
      shapeField: 'smooth',
      xField: 'date',
      yField: 'value',
      style: {
        fill: 'linear-gradient(-90deg, white 0%, #108ee9 100%)',
        fillOpacity: 0.6,
      },
    };
    return <Tiny.Area {...config} />;
  };

  return (
    <>
      {/* <ProCard split="vertical">
        <StatisticCard
          statistic={{
            title: '收录词条记录',
            value: 10,
            description: <></>,
          }}
        />
        <StatisticCard
          chart={TinyAreaChartsView([
            { date: '2024年9月9日', value: 10 },
            { date: '2024年9月10日', value: 2 },
            { date: '2024年9月11日', value: 4 },
            { date: '2024年9月12日', value: 7 },
            { date: '2024年9月13日', value: 6 },
          ])}
        />
        <StatisticCard
          statistic={{
            title: '收录账号 / 检测账号',
            value: `${10} / ${10}`,
            description: <></>,
          }}
        />
      </ProCard> */}
      <ProTable<TophubRecordData.RecordPage>
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        request={async (params = {}, sorter) => {
          const response = await pageTophubRecord({
            ...params,
            source: 1,
            sorter: sorter,
            datahubSourceIds: [rank?.sourceId],
            ...search,
            // hotType: hotType,
          });

          return {
            data: response.data?.data,
            success: true,
            total: response.data?.total,
          };
        }}
        dateFormatter="id"
        defaultSize={'small'}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        toolbar={{
          search: {
            allowClear: true,
            onSearch: (value: string) => {
              setSearch({
                ...search,
                hotName: value,
              });
              actionRef.current?.reloadAndRest();
            },
          },
          filter: (
            <LightFilter
              initialValues={{ createdTime: Date.now(), datahubLevelIds: 0, hotIsCitys: 2 }}
            >
              <ProFormSelect
                name="hotIsCitys"
                label="范围"
                allowClear={false}
                fieldProps={{
                  labelInValue: true,
                  onChange(date) {
                    let Ids;
                    // 如果选择了 '全部'（value 中包含 `0`），设置 levelIds 为 [2000, 3000]
                    if (date.value === '2') {
                      Ids = ['0', '1']; // 注意要转为字符串，所以用 '2000' 和 '3000'
                    } else {
                      // 否则获取其他选择的值
                      Ids = [date.value];
                    }
                    setSearch({
                      ...search,
                      hotIsCitys: Ids,
                    });
                    actionRef.current?.reloadAndRest();
                  },
                }}
                valueEnum={{
                  2: '全部',
                  0: '全国',
                  1: '重庆',
                }}
              />
              <ProFormSelect
                name="datahubLevelIds"
                label="媒体"
                allowClear={false}
                fieldProps={{
                  labelInValue: true,
                  onChange(date) {
                    let levelIds;
                    // 如果选择了 '全部'（value 中包含 `0`），设置 levelIds 为 [2000, 3000]
                    if (date.value === '0') {
                      levelIds = ['2000', '3000']; // 注意要转为字符串，所以用 '2000' 和 '3000'
                    } else {
                      // 否则获取其他选择的值
                      levelIds = [date.value];
                    }
                    setSearch({
                      ...search,
                      datahubLevelIds: levelIds,
                    });
                    actionRef.current?.reloadAndRest();
                  },
                }}
                valueEnum={{
                  0: '全部',
                  2000: '市属媒体',
                  3000: '区县媒体',
                }}
              />
            </LightFilter>
          ),
        }}
        search={false}
        options={{
          density: false,
          setting: false,
        }}
        // pagination={false}
        ghost
      />
    </>
  );
};

export default DetailsRank;
